package com.elysia.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.elysia.common.constant.ProductConstant;
import com.elysia.common.to.SkuHasStockTo;
import com.elysia.common.to.SkuReductionTo;
import com.elysia.common.to.SpuBoundsTo;
import com.elysia.common.to.es.SkuEsModel;
import com.elysia.common.utils.R;
import com.elysia.gulimall.product.entity.*;
import com.elysia.gulimall.product.feign.CouponFeignService;
import com.elysia.gulimall.product.feign.SearchFeignService;
import com.elysia.gulimall.product.feign.WareFeignService;
import com.elysia.gulimall.product.service.*;
import com.elysia.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.common.utils.PageUtils;
import com.elysia.common.utils.Query;

import com.elysia.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存Spu信息
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuBaseInfo(spuInfoEntity);

        //2.保存spu描述图片 pms_spu_info_desc
        List<String> descrImgs=spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity=new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",descrImgs));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3.保存spu图片集 pms_spu_images
        List<String> spuImgs=spuSaveVo.getImages();
        spuImagesService.saveSpuImages(spuInfoEntity.getId(),spuImgs);

        //4.保存spu规格参数 pms_product_attr_value
        List<BaseAttr> baseAttrs=spuSaveVo.getBaseAttrs();
        productAttrValueService.saveSpuBaseAttrs(spuInfoEntity.getId(),baseAttrs);

        //5.保存spu积分信息 gulimall-sms  -> sms_spu_bounds
        Bounds bounds=spuSaveVo.getBounds();
        SpuBoundsTo boundsTo=new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,boundsTo);
        boundsTo.setSpuId(spuInfoEntity.getId());
        if(boundsTo.getBuyBounds().compareTo(new BigDecimal(0))>0 || boundsTo.getGrowBounds().compareTo(new BigDecimal(0))>0){
            if(couponFeignService.saveSpuBounds(boundsTo).getCode()!=0){
                log.error("远程保存spu积分信息失败");
            }
        }

        //6.保存spu对应的所有sku信息
        List<Skus> skus=spuSaveVo.getSkus();
        if(skus!=null && !skus.isEmpty()){
            skus.forEach(sku->{
                String defaultImg="";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                        break;
                    }
                }

                //6.1 sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity=new SkuInfoEntity();
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId=skuInfoEntity.getSkuId();
                //6.2 sku 图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(item->{
                    return !StringUtils.isEmpty(item.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                //6.3 sku销售属性信息 pms_sku_sale_attr_value
                List<Attr> saleAttrs=sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = saleAttrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                //6.4 sku的优惠、满减等信息： gulimall-sms  -> sms_sku_ladder sms_sku_full_reduction sms_member_price
                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>=0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))>0){
                    if(couponFeignService.saveSkuReduction(skuReductionTo).getCode()!=0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }

    }

    @Override
    public void saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void up(Long spuId) {

        //获取  可被检索的 规格属性
        List<ProductAttrValueEntity> baseAttrs  = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(baseAttr -> {
            return baseAttr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> searchBaseAttrs = baseAttrs.stream().filter(baseAttr -> {
            return idSet.contains(baseAttr.getAttrId());
        }).map(baseAttr ->{
            SkuEsModel.Attr attr=new SkuEsModel.Attr();
            BeanUtils.copyProperties(baseAttr,attr);
            return attr;
        }).collect(Collectors.toList());

        List<SkuInfoEntity> skuList = skuInfoService.getSkusBySpuId(spuId);
        //远程调用ware 获取库存状态 hasStock
        List<Long> skuIds = skuList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        List<SkuHasStockTo> skuHasStockTos = null;
        Map<Long,Boolean> stockMap = null;
        try{
            R r =  wareFeignService.hasStock(skuIds);
            TypeReference<List<SkuHasStockTo>> typeReference =new TypeReference<List<SkuHasStockTo>>(){};
            skuHasStockTos= r.getData(typeReference);
            stockMap = skuHasStockTos.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        }catch (Exception e){
            log.error("远程调用Ware库存服务异常，原因:{ }",e);
        }
        Map<Long, Boolean> finalStockMap = stockMap;

        List<SkuEsModel> collect = skuList.stream().map(skuInfoEntity -> {
            //组装 skuEsModel
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            //skuPrice,skuImg,brandName,brandImg,catalogName,attrs
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            BrandEntity skuBrand = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(skuBrand.getName());
            skuEsModel.setBrandImg(skuBrand.getLogo());

            skuEsModel.setCatalogName(categoryService.getById(skuEsModel.getCatalogId()).getName());
            if(finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else{
                skuEsModel.setHasStock(finalStockMap.get(skuEsModel.getSkuId()));
            }

            //TODO 热度hotScore
            skuEsModel.setHotScore(0L);

            //可检索 baseAttr
            skuEsModel.setAttrs(searchBaseAttrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        // 远程调用search 将sku存储在es中
        try {
            R searchR = searchFeignService.productUP(collect);
            if (searchR.getCode() == 0){
                //修改spu在 pms 数据库 中的 状态
                this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            }else{
                log.error("商品上架，保存至es失败");
            }
        }catch (Exception e){
            log.error("调用远程服务search异常,原因:{}",e);
        }

    }

}